package com.cxb.demotest.controller;

import com.cxb.demotest.annotations.AccessLimit;
import com.cxb.demotest.dao.entity.UserOneDO;
import com.cxb.demotest.exception.HelloRetryException;
import com.cxb.demotest.service.UserService;
import com.cxb.demotest.util.DateUtil;
import com.cxb.demotest.util.RedisUtil;
import com.github.rholder.retry.Retryer;
import com.github.rholder.retry.RetryerBuilder;
import com.github.rholder.retry.StopStrategies;
import com.github.rholder.retry.WaitStrategies;
import com.github.rholder.retry.WaitStrategy;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Xbao
 * @version 1.0
 * @description test
 * @date 2021/3/8 17:07
 */
@RestController
@RequestMapping("/main")
@Slf4j
public class Controller {

  @Autowired
  private RedisUtil redisUtil;

  @Autowired
  private UserService userService;

  @GetMapping("test")
  public String test(){
    redisUtil.set("current_time", DateUtil.parseDateTimeStr(LocalDateTime.now()));

    // test spring retryable
    String text = userService.helloWithSpringRetry();

    // test guava retry
//    Retryer<String> retryer = RetryerBuilder.<String>newBuilder()
//        .retryIfExceptionOfType(HelloRetryException.class)
//        .retryIfResult(StringUtils::isEmpty)
//        .withWaitStrategy(WaitStrategies.fixedWait(3, TimeUnit.SECONDS))
//        .withStopStrategy(StopStrategies.stopAfterAttempt(5))
//        .build();
//    String text = "null";
//    try{
//      final String text1 = retryer.call(() -> userService.helloWithGuavaRetry());
//      text = text1;
//    } catch (Exception e){
//      e.printStackTrace();
//    }

    return text;
  }

  @GetMapping("avoidFlush")
  @AccessLimit(seconds = 5, maxTimes = 5)
  public String avoidFlush(){

    return "Hello,World";

  }

  @GetMapping("test1")
  public Long test1(String expression){
    String[] ss = expression.split("\\+");
    System.out.println(expression + " => " + Arrays.toString(ss));
    long sum = 0;
    for (String s: ss) {
      sum += Integer.parseInt(s.trim());
    }
    return sum;
  }

  @GetMapping("test2")
  public String test2(){
    return userService.queryAllNames();
  }

  @GetMapping("test3")
  public String test3(@RequestParam String day1,String day2){

    Date current = new Date();

    String thisMonthDate = day1;
    String nextMonthDate = day2;

    Calendar thisMonthDateCalendar = Calendar.getInstance();
    thisMonthDateCalendar.setTime(current);
    thisMonthDateCalendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(thisMonthDate));
    thisMonthDateCalendar.set(Calendar.HOUR_OF_DAY, 23);
    thisMonthDateCalendar.set(Calendar.MINUTE, 59);
    thisMonthDateCalendar.set(Calendar.SECOND, 59);
    System.out.println("this:"+DateUtil.parseDateTimeStr(thisMonthDateCalendar.getTime()));


    Calendar nextMonthDateCalendar = Calendar.getInstance();
    nextMonthDateCalendar.setTime(DateUtils.addMonths(thisMonthDateCalendar.getTime(), 1));
    nextMonthDateCalendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(nextMonthDate));

    System.out.println("this:"+DateUtil.parseDateTimeStr(thisMonthDateCalendar.getTime()));
    System.out.println("next:"+DateUtil.parseDateTimeStr(nextMonthDateCalendar.getTime()));


//    int redundantDay = 0;
//    if(thisMonthDateCalendar.get(Calendar.DAY_OF_MONTH) > lastMonthDateCalendar.get(Calendar.DAY_OF_MONTH)){
//      redundantDay = thisMonthDateCalendar.get(Calendar.DAY_OF_MONTH) - lastMonthDateCalendar.get(Calendar.DAY_OF_MONTH);
//    }
//    lastMonthDateCalendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(thisMonthDate) - redundantDay);

//    System.out.println("this:"+DateUtil.parseDateTimeStr(thisMonthDateCalendar.getTime()));
//    System.out.println("last:"+DateUtil.parseDateTimeStr(nextMonthDateCalendar.getTime()));


    return "1";
//    return userService.queryAllNames();
  }

  @GetMapping("test4")
  public String test4(){
    String uri = "mongodb://testAdmin:123456@127.0.0.1:27017/admin?retryWrites=true&writeConcern=majority";

    try (MongoClient mongoClient = MongoClients.create(uri)) {
      // database and collection code goes here
      MongoDatabase db = mongoClient.getDatabase("admin");
      MongoCollection<Document> coll = db.getCollection("system.users");

      // find code goes here
      MongoCursor<Document> cursor = coll.find().iterator();

      // iterate code goes here
      try {
        while (cursor.hasNext()) {
          System.out.println(cursor.next().toJson());
        }
      } finally {
        cursor.close();
      }
    }
    return "success";
  }

  @GetMapping("test5")
  public String test5(){
    UserOneDO userOneDO = new UserOneDO();
    userOneDO.setId(1);
    userOneDO.setName("mm");
    return userOneDO.toString();
  }


}
